package com.anjubao.parking.municipal.user.config;

import com.anjubao.parking.municipal.user.component.lock.DistributedLocker;
import lombok.extern.slf4j.Slf4j;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * redisson分布式锁
 *
 * @author zhuchunfeng
 * @date 2019/6/25 16:36
 */
@Configuration
@Slf4j
public class RedissonConfiguration {

    @Value("${spring.redis.cluster.nodes:}")
    private String cluster;

    @Bean
    public RedissonClient getRedisson() {

        String[] nodes = cluster.split(",");
        //redisson版本是3.5，集群的ip前面要加上“redis://”，不然会报错，3.2版本可不加
        for (int i = 0; i < nodes.length; i++) {
            nodes[i] = "redis://" + nodes[i];
        }
        RedissonClient redisson = null;
        Config config = new Config();
        config.useClusterServers() //这是用的集群server
                .setScanInterval(2000) //设置集群状态扫描时间
                .addNodeAddress(nodes);
        redisson = Redisson.create(config);
        //可通过打印redisson.getConfig().toJSON().toString()来检测是否配置成功
        return redisson;
    }

    @Bean
    public DistributedLocker distributedLocker(RedissonClient redissonClient) {
        return new DistributedLocker(redissonClient);
    }

}
